package com.example.demogateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * IP白名单，即IP限流
 */
@Component
public class IpWhitelistFilter extends ZuulFilter {

    private Logger logger = LogManager.getLogger(getClass());
    private static List<String> ipWhiteList = new ArrayList<>();

    /**
     * 为了方便演示，此处固定写死白名单内容，正常来说是读外部数据库，比如mysql、redis等
     */
    static {
        ipWhiteList.add("127.0.0.1");
        ipWhiteList.add("localhost");
    }

    /**
     * pre：在请求被路由（转发）之前调用
     * route：在路由（请求）转发时被调用
     * error：服务网关发生异常时被调用
     * post：在路由（转发）请求后调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String remoteHost = request.getRemoteHost();    //获取请求IP
        logger.log(Level.INFO, request.getMethod() + " request ip : {}", remoteHost);
        if (!(ipWhiteList.contains(remoteHost))) {
            logger.log(Level.WARN, request.getMethod() + " request from " + remoteHost + " is unauthorized.");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            return null;
        }
        logger.log(Level.INFO, "access ip ok");
        return null;
    }

}
